//
//  MqFindBikeShopDetailViewController.m
//  Meiqi
//
//  Created by lanou on 16/1/14.
//  Copyright © 2016年 KFC. All rights reserved.
//

#import "MqFindBikeShopDetailViewController.h"
#import "MqFindBikeShopDetailModel.h"
#import "MqFindBikeShopdeatailPhotoModel.h"
#import "MqFindBikeShopDetailCommentModel.h"
#import "MqFindBikeShopDetailHeaderView.h"
#import "DCPicScrollView.h"
#import "DCWebImageManager.h"
#import "MqFBMapViewController.h"
#import "MqFindBikeShopDetailTableViewCell.h"
@interface MqFindBikeShopDetailViewController () <UITableViewDataSource, UITableViewDelegate>

@property (nonatomic ,strong)NSMutableArray *photoArray;

@property (nonatomic, strong) NSString *lon;
@property (nonatomic, strong) NSString *lat;

@property (nonatomic ,strong)NSMutableArray *commentArray;

@property (nonatomic ,strong)UITableView *tableView;

@property (nonatomic ,strong)MqFindBikeShopDetailHeaderView *shopdetail;

@property (nonatomic ,strong)UIWebView *webView;

@property (nonatomic ,strong)NSString *urlString;


@property (nonatomic ,strong)UITextField *text;

@property (nonatomic ,strong)UIView *input;

@property (nonatomic ,strong)UITextView *textView;


@end

@implementation MqFindBikeShopDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //  加载数据
    [self setUpData];
    //  添加表视图
    [self addTableView];
    //  添加键盘上的inputView
    [self addInputView];
}
//  加载数据
- (void)setUpData
{
    NSString *url = [NSString stringWithFormat:@"http://s.biketo.com/api/app/shop?access_token=(null)&shop_id=%@",self.shop_id];
    
    [PKRequestManager requestWithUrlString:url parDic:nil Method:GET finish:^(NSData *data) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        
        NSDictionary *dataDic = dic[@"data"];
        
        //  经纬度
        _lon = dataDic[@"lon"];
        _lat = dataDic[@"lat"];
        
        MqFindBikeShopDetailModel *model = [[MqFindBikeShopDetailModel alloc] init];
        
        [model setValuesForKeysWithDictionary:dataDic];
        
        
        _shopdetail.nameLabel.text = model.name;
        _shopdetail.cate_nameLabel.text = model.cate_name;
        if ([model.cate_cog isEqualToString:@"blue"]) {
            
            _shopdetail.cate_nameLabel.backgroundColor = [UIColor blueColor];
        }
        if ([model.cate_cog isEqualToString:@"red"]) {
            _shopdetail.cate_nameLabel.backgroundColor = [UIColor redColor];
        }
        
        NSInteger num = [model.stars integerValue];
        for (int i = 0; i < num; i ++) {
            UIImageView *star = [_shopdetail.starsLabel viewWithTag:50 + i];
            star.image = [UIImage imageNamed:@"icon_shop_detail_rate@3x"];
        }
        
        if ([model.times isEqualToString:@"0"]) {
            _shopdetail.evaluateLabel.text = @"暂未评价";
        }else
        {
            _shopdetail.evaluateLabel.text = [NSString stringWithFormat:@"%@评价",model.times];
        }
        
        _urlString = [NSString stringWithFormat:@"tel://%@",model.contact];
        
        [_shopdetail.addressButton setTitle:[NSString stringWithFormat:@"       %@",model.address] forState:(UIControlStateNormal)];
        
        //  点击地图按钮
        [_shopdetail.addressButton addTarget:self action:@selector(mapClick:) forControlEvents:(UIControlEventTouchUpInside)];
        _shopdetail.business_hoursLabel.text = [NSString stringWithFormat:@"营业时间: %@",model.business_hours];
        
        //  自定义高度
        _shopdetail.brandsLabel.text = [NSString stringWithFormat:@"主营品牌:%@",model.brands];
        [_shopdetail.brandsLabel sizeToFit];
        CGFloat brandHeight = _shopdetail.brandsLabel.frame.size.height;
        [_shopdetail.brandsLabel setFrame:CGRectMake(10, 470, kScreenWidth - 20, brandHeight)];
        _shopdetail.descriptionLabel.text = [NSString stringWithFormat:@"店铺介绍:%@",model.descriPtion];
        
        //  自定义高度
        [_shopdetail.descriptionLabel sizeToFit];
        CGFloat desHeight = _shopdetail.descriptionLabel.frame.size.height;
        
        //  重新设置scrollView的frame
        [_shopdetail.scrollView setFrame:CGRectMake(0, 0, kScreenWidth, desHeight + _shopdetail.brandsLabel.bottom + 10)];
        //  重新设置descriptionLabel的frame
        [_shopdetail.descriptionLabel setFrame:CGRectMake(10, _shopdetail.brandsLabel.bottom + 10, kScreenWidth - 20, desHeight)];
        
        //  重新设置表头的frame
        [_shopdetail setFrame:CGRectMake(0, 0, kScreenWidth, desHeight + _shopdetail.brandsLabel.bottom + 10)];
        
        //表头轮播图
        NSArray *array = dataDic[@"photos"];
        _photoArray = [NSMutableArray array];
        for (NSDictionary *oneDic in array) {
//            MqFindBikeShopdeatailPhotoModel *model = [[MqFindBikeShopdeatailPhotoModel alloc] init];
//            [model setValuesForKeysWithDictionary:oneDic];
//            [_photoArray addObject:model];
            NSString *url = oneDic[@"photo_url"];
            [_photoArray addObject:url];
            
        }
        //  第三方
        DCPicScrollView *ScrollView = [DCPicScrollView picScrollViewWithFrame:CGRectMake(0, 0, kScreenWidth, 250) WithImageUrls:_photoArray];
        //  设置延迟时间
        ScrollView.AutoScrollDelay = 2;
        
        [_shopdetail.picView addSubview:ScrollView];
        
        
        //  重新赋值表头
          _tableView.tableHeaderView = _shopdetail;
        
        NSArray *arr = dataDic[@"comment_list"][@"data"];
        _commentArray = [NSMutableArray array];
        if ([dataDic[@"comment_list"][@"count"] isEqualToString:@"0"]) {
            
        }else
        {
            for (NSDictionary *twoDic in arr) {
                MqFindBikeShopDetailCommentModel *model = [[MqFindBikeShopDetailCommentModel alloc] init];
                [model setValuesForKeysWithDictionary:twoDic];
                [_commentArray addObject:model];
            }
        }
        
        
        [self.tableView reloadData];
    } error:^(NSError *error) {
        
    } path:@"ShopDetail"];
    
}

//  点击地图按钮
- (void)mapClick:(UIButton *)button
{
    MqFBMapViewController *mapVC = [[MqFBMapViewController alloc] init];
    mapVC.lon = [_lon floatValue];
    mapVC.lat = [_lat floatValue];
    [self.navigationController pushViewController:mapVC animated:YES];
    
    
}


//  拨打电话点击方法
- (void)telephoneButtonClick:(UIButton *)button
{
    
    if (_webView == nil) {
        _webView = [[UIWebView alloc]init];
        
        NSURL *url = [NSURL URLWithString:_urlString];
        //  创建一个请求
        NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
        //  通过请求加载webView
        [_webView loadRequest:request];
        
    } else {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示信息" message:@"该设备不支持电话功能" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alert show];
    }
}



//添加TableView;
- (void)addTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 50)];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    
    _shopdetail = [[MqFindBikeShopDetailHeaderView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 300)];
    _tableView.tableHeaderView = _shopdetail;
    
    [self.view addSubview:_tableView];
    [_shopdetail.telephoneButton addTarget:self action:@selector(telephoneButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    

    
}

#pragma mark --tableView代理方法

//分区数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

//行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _commentArray.count;
}

//设置cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MqFindBikeShopDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    if (cell == nil) {
        cell = [[MqFindBikeShopDetailTableViewCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:@"Cell"];
    }
    MqFindBikeShopDetailCommentModel *model = _commentArray[indexPath.row];
    cell.model = model;
    
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSString *str = @"最新评论";
    return str;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:15], NSFontAttributeName, nil];
    
    MqFindBikeShopDetailCommentModel *model = _commentArray[indexPath.row];
    CGRect frame = [model.content boundingRectWithSize:CGSizeMake(kScreenWidth - 90, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    if ([model.reply_to_username isEqualToString:@""]) {
        return 70 + frame.size.height;
    }else
    {
        return 110 + frame.size.height;
    }
    
}

#pragma mark -- 键盘输入inputView

- (void)addInputView
{
    UILabel *Label = [[UILabel alloc] initWithFrame:CGRectMake(0, kScreenHeight - 50, kScreenWidth, 50)];
    //Label.backgroundColor = [UIColor lightGrayColor];
    Label.userInteractionEnabled = YES;
    [self.view addSubview:Label];
    
    _text = [[UITextField alloc] initWithFrame:CGRectMake(10, 5, kScreenWidth - 20, 40)];
    _text.placeholder = @"请输入...";
    [_text.layer setCornerRadius:10];
    //_text.backgroundColor = [UIColor whiteColor];
    [Label addSubview:_text];
    
    
    _input = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 300)];
//    _input.backgroundColor = [UIColor whiteColor];
    _text.inputAccessoryView = _input;
    
    UIButton *cancel = [UIButton buttonWithType:(UIButtonTypeCustom)];
    cancel.frame = CGRectMake(10, 10, (kScreenWidth - 40) / 3, 30);
    [cancel setTitle:@"取消" forState:(UIControlStateNormal)];
    [cancel addTarget:self action:@selector(cancelClick:)
     forControlEvents:(UIControlEventTouchUpInside)];
    [cancel setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
    [_input addSubview:cancel];
    
    
    
    UILabel *Label2 = [[UILabel alloc] initWithFrame:CGRectMake(20 + (kScreenWidth - 40) / 3, 10, (kScreenWidth - 40) / 3, 30)];
    Label2.text = @"写评论";
    Label2.textAlignment = NSTextAlignmentCenter;
    //Label2.backgroundColor = [UIColor greenColor];
    [_input addSubview:Label2];
    
    UIButton *send = [UIButton buttonWithType:(UIButtonTypeCustom)];
    send.frame = CGRectMake(30 + 2 * (kScreenWidth - 40) / 3, 10, (kScreenWidth - 40) / 3, 30);
    [send setTitle:@"发送" forState:(UIControlStateNormal)];
    [send setTitleColor:[UIColor redColor] forState:(UIControlStateNormal)];
    [send addTarget:self action:@selector(sendClick:) forControlEvents:(UIControlEventTouchUpInside)];
    [_input addSubview:send];
    
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 50, 70, 30)];
    label.text = @"车店评分";
    label.textColor = [UIColor blackColor];
    [_input addSubview:label];
    for (int i = 0; i < 5; i ++) {
        UIButton *star = [UIButton buttonWithType:(UIButtonTypeCustom)];
        star.frame = CGRectMake(90 + 30 * i, 50 , 30, 30);
        star.tag = 10000 + i;
        
        [star setImage:[UIImage imageNamed:@"icon_shop_detail_noRate@3x"] forState:(UIControlStateNormal)];
        
        [star addTarget:self action:@selector(starChange:) forControlEvents:(UIControlEventTouchUpInside)];
        
        [_input addSubview:star];
        
    }
    
    
    _textView = [[UITextView alloc] initWithFrame:CGRectMake(10, 100, kScreenWidth - 20, 190)];
    //_textView.backgroundColor = [UIColor lightGrayColor];
    
    [_textView.layer setCornerRadius:10];
    [_input addSubview:_textView];
    
    
}

- (void)starChange:(UIButton *)star
{
    for (int i = 0; i < 5; i ++) {
        UIButton *button = [_input viewWithTag:10000 + i];
        [button setImage:[UIImage imageNamed:@"icon_shop_detail_noRate@3x"] forState:(UIControlStateNormal)];
        
    }
    
    
    NSInteger x = star.tag - 10000;
    NSLog(@"%ld",(long)x);
    for (int i = 0; i <= x; i ++) {
        UIButton *button = [_input viewWithTag:10000 + i];
        [button setImage:[UIImage imageNamed:@"icon_shop_detail_rate@3x"] forState:(UIControlStateNormal)];
    }
}


- (void)cancelClick:(UIButton *)cancel
{
    [_textView resignFirstResponder];
    [_text resignFirstResponder];
}

- (void)sendClick:(UIButton *)send
{
    
}


- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [_textView endEditing:YES];
    
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
